<?php

/**
 * Seeds the dmBridge data store with fixture data. Modules can subclass
 * this and override seed() to seed their own data.
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMTestDataSeeder {

	/**
	 * @return A reasonably random 10-digit alphanumeric string.
	 */
	protected static function getRandomValue() {
		return substr(md5(rand(1, 1000000)), 0, 10);
	}

	/**
	 * @param string data_store One of "sqlite" or "mysql". Configuration is
	 * taken from config.php.
	 */
	public function __construct($data_store = "sqlite") {
		switch ($data_store) {
		case "sqlite":
			$this->initializeDmBridgeWithSQLiteDataStore();
			break;
		case "mysql":
			$this->initializeDmBridgeWithMySQLDataStore();
			break;
		}
	}

	protected function initializeDmBridgeWithMySQLDataStore() {
		$config = DMConfigIni::getInstance();
		$config->setString("dmbridge.database.engine", "pdo_mysql");
		$config->setString("dmbridge.database.mysql.host", TEST_DB_HOST);
		$config->setString("dmbridge.database.mysql.name", TEST_DB_NAME);
		$config->setString("dmbridge.database.mysql.password", TEST_DB_PASS);
		$config->setString("dmbridge.database.mysql.port", TEST_DB_PORT);
		$config->setString("dmbridge.database.mysql.username", TEST_DB_USER);
	}

	protected function initializeDmBridgeWithSQLiteDataStore() {
		$config = DMConfigIni::getInstance();
		$config->setString("dmbridge.database.engine", "pdo_sqlite");
	}

	/**
	 * Seeds the data store with fixture data.
	 */
	public function seed() {
		$this->wipe();

		$col = DMCollectionFactory::getCollection(TEST_ALIAS);
		$obj = DMObjectFactory::getObject($col, TEST_PTR);

		$num_objects = 200;
		for ($i = 1; $i <= $num_objects; $i++) {
			$comment = new DMComment();
			$comment->setID($i);
			$comment->setEmail("test@example.com");
			$comment->setName(self::getRandomValue());
			$comment->setValue(self::getRandomValue());
			$comment->setApproved($i > 10);
			$obj->addComment($comment);

			// add $i ratings to the static object
			$rating = new DMRating(rand(0, 100), 100);
			$rating->setID($i);
			$obj->addRating($rating);

			// add one rating to each dynamic object
			$rating = new DMRating(rand(0, 100), 100);
			$rating->setID($i + $num_objects);
			$dobj = DMObjectFactory::getObject(
					DMCollectionFactory::getCollection(TEST_DYNAMIC_ALIAS), $i);
			$dobj->addRating($rating);

			$tag = new DMTag();
			$tag->setID($i);
			$tag->setValue(self::getRandomValue());
			$tag->setApproved($i > 10);
			$obj->addTag($tag);
		}
	}

	public function wipe() {
		$ds = DMDataStoreFactory::getDataStore();
		if (($ds instanceof DMSQLiteDataStore && file_exists($ds->getPath()))
				|| !($ds instanceof DMSQLiteDataStore)) {
			$ds->write("DELETE FROM comment", array());
			$ds->write("DELETE FROM rating", array());
			$ds->write("DELETE FROM tag", array());
		}
	}

}
